<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\AdminBaseController;
use App\Http\Requests\UserRequest;
use App\Models\AdminUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Role;

/**
 * 后台管理员控制器
 * Class UserController
 * @package App\Http\Controllers\Admin
 */
class UserController extends AdminBaseController
{
    // 无需登录的方法
    protected $noNeedLogin = [];

    // 无需鉴权的方法
    protected $noNeedRight = [];
    /**
     * 分页查询管理员列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $page = $request->get('page', 1);
        $pageSize = $request->get('pageSize', 20);
        $user = new AdminUser();

        // 查询条件
        $filter = $request->all();
        $where = [];
        isset($filter['username']) && !empty($filter['username']) ? $where[] = ['username', '=', $filter['username']] : [];
        isset($filter['nickname']) && !empty($filter['nickname']) ? $where[] = ['nickname', 'like', '%' . $filter['nickname'] . '%'] : [];
        isset($filter['mobile']) && !empty($filter['mobile']) ? $where[] = ['mobile', 'like', '%' . $filter['mobile'] . '%'] : [];
        $query = $user->where($where);
        $count = $query->count();
        $start = ($page - 1) * $pageSize; // 起始查询
        // 当前页查询列表
        $list = $query->with('roles')->skip($start)->take($pageSize)->get();
        $result = [
            'page' => $page,
            'pageSize' => $pageSize,
            'count' => $count,
            'list' => $list
        ];
        return $this->success($result);
    }

    /**
     * 新增管理员用户
     * @param UserRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(UserRequest $request)
    {
        $param = $request->all();
        $param['password'] = Hash::make($param['password']);
        $user = AdminUser::create($param);
        if (isset($param['roles'])) {
            $user->roles()->sync($param['roles']);
        }
        return $this->success($user, '添加管理员成功');
    }

    /**
     * 更新管理员用户
     * @param UserRequest $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(UserRequest $request, $id)
    {
        $param = $request->all();
        $user = AdminUser::findOrFail($id);
        if (isset($param['password'])) {
            $param['password'] = Hash::make($param['password']);
        }
        $user->fill($param)->save();
        if (isset($param['roles'])) {
            $user->roles()->sync($param['roles']);
        }
        return $this->success($user, '更新管理员资料成功');
    }

    /**
     * 删除管理员
     */
    public function destroy($id)
    {
        $user = AdminUser::findOrFail($id);
        $user->delete();
        return $this->success(null,'删除管理员成功');
    }

}
